import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lib_core/multi_engine/gt_multi_engine_sync.dart';
import 'package:lib_furnace/gt_router.dart';

enum GTNativeDialogHelperType {
  nativeDialogClose,
}

class GTNativeDialogHelper {
  static Function(Map<String, dynamic> map)? lastCallBack;

  ///目前只支持 全局最多1个Dialog弹窗
  ///注意1:dialogRouteName指向的页面需要有GTNativeDialogWrap包裹
  ///注意2:此方法show的,请使用此方法的pop 结对使用;
  static void show({
    required BuildContext context,
    required String dialogRouteName,
    required Map<String, dynamic> params,
    required Function(Map<String, dynamic> map) callBack,
    bool noAnimation = true,
  }) async {
    lastCallBack = callBack;
    //防止之前的弹窗没有走pop方法, 先尝试移除一次监听
    GTMultiEngineSyncer.removeListen(GTNativeDialogHelperType.nativeDialogClose, _handleClick);
    GTMultiEngineSyncer.addListen(GTNativeDialogHelperType.nativeDialogClose, _handleClick);

    if (context.mounted) {
      GTRouter.push(
        context,
        dialogRouteName,
        arguments: params,
        newContainer: true,
        isDialog: true,
        noAnimation: noAnimation,
      );
    }
  }

  static Future<void> pop(Map<String, dynamic> arguments) async {
    //此方法体 运行在其他引擎里
    GTMultiEngineSyncer.notifyToSync(GTNativeDialogHelperType.nativeDialogClose, arguments);
    await SystemNavigator.pop(animated: false);
  }

  static void _handleClick(Map<String, dynamic> arguments) {
    //当且引擎收到通知后, 通知callBack, 然后移除监听
    if (lastCallBack != null) {
      lastCallBack!(arguments);
    }
    GTMultiEngineSyncer.removeListen(GTNativeDialogHelperType.nativeDialogClose, _handleClick);
  }
}
